package com.shujiaotong.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shujiaotong.common.R;

import com.shujiaotong.pojo.Category;
import com.shujiaotong.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    //分页
    @RequestMapping("page")
    public Object page(@RequestParam int page,
                       @RequestParam int pageSize,
                       @RequestParam(required = false,value = "name") String name){
//        接收参数
        log.info("当前页:{},页条数:{},活动:{}",page,pageSize,name);
//        分页条件
        Page<Category> categoryPage = new Page<>(page,pageSize);
//        查询条件
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name),Category::getName,name);
//        分页查询
        categoryService.page(categoryPage,qw);
//        返回值
        return R.success(categoryPage);

    }
//    新增
    @PostMapping
    public R save(@RequestBody Category category){
//        log.info("新增分类:{}",category);
        boolean save = categoryService.save(category);
        return save?R.success("新增成功"):R.error("新增失败");
    }

//    根据id查询
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id ){
        log.info("根据id查询活动:{}",id);
        Category category = categoryService.getById(id);
        return R.success(category);
    }

//    修改
    @PutMapping
    public R update(@RequestBody Category category){
        log.info("修改分类:{}",category);
        boolean b = categoryService.updateById(category);
        return b?R.success("修改成功"):R.error("修改失败");
    }
//    删除
    @DeleteMapping
    public R delete(Long id){
        log.info("删除分类:{}",id);
        boolean b = categoryService.removeById(id);
        return b?R.success("删除成功"):R.error("删除失败");
    }

//    查询全部
    @GetMapping
    public R list(){
        log.info("查询全部分类");
        return R.success(categoryService.list());
    }
}
